import 'package:flutter/widgets.dart';
import 'package:pkg_obz/core/rx_obj.dart';

typedef WidgetCallback = Widget Function();

abstract class _ObzWidget extends StatefulWidget {
  const _ObzWidget({Key? key}) : super(key: key);

  //创建状态
  @override
  _ObzState createState() => _ObzState();

  //创建widget
  @protected
  Widget build();
}

class _ObzState extends State<_ObzWidget> {
  RxObserver? _observer;

  ///构造函数
  _ObzState() {
    _observer = RxObserver();
  }

  ///初始化
  @override
  void initState() {
    _observer!.observe(_updateUI);
    super.initState();
  }

  ///刷新UI
  void _updateUI() {
    if (mounted) {
      setState(() {});
    }
  }

  ///页面销毁
  @override
  void dispose() {
    _observer?.close();
    super.dispose();
  }

  ///创建widget，在这里进行状态观察的绑定
  Widget get buildWidgets {
    //获取proxy原来的值，也就是null
    final observer = RxObserver.proxy;

    //把widget的观察者赋值过去
    RxObserver.proxy = _observer;

    //在widget.build()的时机进行绑定
    final widgets = widget.build();

    //绑定后恢复proxy的值，避免其他widget引用出现错误
    RxObserver.proxy = observer;

    return widgets;
  }

  @override
  Widget build(BuildContext context) => buildWidgets;
}

class Obz extends _ObzWidget {
  final WidgetCallback builder;

  const Obz(this.builder, {Key? key}) : super(key: key);

  @override
  Widget build() => builder();
}
